package com.zhoutao.blog.seven.pages;

import com.zhoutao.blog.seven.dao.model.ArticleDao;
import com.zhoutao.blog.seven.dao.repository.ArticleRepository;
import com.zhoutao.blog.seven.dao.repository.TagRelationRepository;
import com.zhoutao.blog.seven.model.enums.RefType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Controller
public class TestPageController extends AbstractPageController {

    @Autowired
    private ArticleRepository articleRepository;

    @Autowired
    private TagRelationRepository tagRelationRepository;

    @GetMapping("/test")
    public String index(Model model) {
        packageBaseInfo(model);
        model.addAttribute("name", "123");

        List<ArticleDao> list = articleRepository.list();
        for (ArticleDao articleDao : list) {
            List<String> keys = findTags(articleDao.getKeys());
            if (CollectionUtils.isEmpty(keys)) {
                continue;
            }
            tagRelationRepository.updateTagRelation(articleDao.getId(), RefType.ARTICLE, keys);
        }
        return "about";
    }

    public List<String> findTags(String keys) {
        if (keys == null || keys.trim().length() == 0) {
            return Collections.emptyList();
        }
        String[] tags = keys.split(";");
        for (int i = 0; i < tags.length; i++) {
            String tag = tags[i];
            if (tag == null || tag.trim().length() == 0) {
                continue;
            }
            tags[i] = tag.trim();
        }
        return Arrays.asList(tags);
    }
}
